package com.cy.ppj.service.order.impl;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

import com.alibaba.druid.sql.visitor.functions.Now;
import com.cy.ppj.comm.constant.Constants;
import com.cy.ppj.comm.exception.MsgException;
import com.cy.ppj.comm.utils.CommonUtils;
import com.cy.ppj.comm.utils.JsonObjectMapper;
import com.cy.ppj.comm.utils.SpringContextUtils;
import com.cy.ppj.dao.mapper.account.UserOrderInfoMapper;
import com.cy.ppj.dao.mapper.manager.ManagerMapper;
import com.cy.ppj.model.domian.account.UserOrderInfo;
import com.cy.ppj.model.domian.user.User;
import com.cy.ppj.model.domian.user.UserInfo;
import com.cy.ppj.model.dto.statistics.StatisticsUserLoanAmountDTO;
import com.cy.ppj.model.dto.customer.CustomerOrderDTO;
import com.cy.ppj.model.dto.customer.CustomerOrderScanRecordDTO;
import com.cy.ppj.model.query.order.DecorationPassOrderListAdminQuery;
import com.cy.ppj.model.query.order.OrderCountQuery;
import com.cy.ppj.model.query.order.OrderScanRecordAdminQuery;
import com.cy.ppj.model.query.order.OrderScanRecordQuery;
import com.cy.ppj.model.query.order.OrderWithholdAdminQuery;
import com.cy.ppj.model.vo.admin.order.DecorationPassOrderListAdminVO;
import com.cy.ppj.model.vo.admin.order.OrderScanRecordAdminVO;
import com.cy.ppj.model.vo.admin.order.OrderScanRecordVO;
import com.cy.ppj.model.vo.admin.order.OrderWithholdAdminVO;
import com.cy.ppj.model.vo.customer.CustomerContactInfoVO;
import com.cy.ppj.model.vo.customer.CustomerImageListVO;
import com.cy.ppj.model.vo.order.FurnitureGoodsOrderDetailAdminVO;
import com.cy.ppj.model.vo.order.OrderImageListVO;
import com.cy.ppj.service.account.BrokerService;
import com.cy.ppj.service.account.CertificationService;
import com.cy.ppj.service.account.CommissionService;
import com.cy.ppj.service.account.UserInfoService;
import com.cy.ppj.service.comm.FileService;
import com.cy.ppj.service.dict.DictService;
import com.cy.ppj.service.statistics.StatisticsService;

import lombok.extern.slf4j.Slf4j;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import com.cy.ppj.dao.mapper.order.OrderAuditRecordMapper;
import com.cy.ppj.dao.mapper.order.OrderExtMapper;
import com.cy.ppj.dao.mapper.order.OrderImageMapper;
import com.cy.ppj.dao.mapper.order.OrderMapper;
import com.cy.ppj.dao.mapper.order.OrderManagerMapper;
import com.cy.ppj.dao.mapper.order.OrderWithholdMapper;
import com.cy.ppj.dao.mapper.product.ProductMapper;
import com.cy.ppj.dao.mapper.product.ProductRateMapper;
import com.cy.ppj.dao.mapper.customer.CustomerContactMapper;
import com.cy.ppj.dao.mapper.customer.CustomerImageMapper;
import com.cy.ppj.dao.mapper.customer.CustomerMapper;
import com.cy.ppj.dao.mapper.user.UserInfoMapper;
import com.cy.ppj.dao.mapper.user.UserMapper;
import com.cy.ppj.model.PageBean;
import com.cy.ppj.model.Result;
import com.cy.ppj.model.ao.order.OrderAdminAddAO;
import com.cy.ppj.model.ao.order.OrderAdminEditAO;
import com.cy.ppj.model.ao.order.OrderAuditAO;
import com.cy.ppj.model.ao.order.OrderExtSetAO;
import com.cy.ppj.model.ao.order.OrderScanRecordComfirmAO;
import com.cy.ppj.model.ao.order.OrderWithholdSetAO;
import com.cy.ppj.model.domian.admin.Manager;
import com.cy.ppj.model.domian.order.Order;
import com.cy.ppj.model.domian.order.OrderAuditRecord;
import com.cy.ppj.model.domian.order.OrderExt;
import com.cy.ppj.model.domian.order.OrderManager;
import com.cy.ppj.model.domian.order.OrderWithhold;
import com.cy.ppj.model.domian.product.ProductRate;
import com.cy.ppj.model.domian.customer.Customer;
import com.cy.ppj.model.domian.customer.CustomerContact;
import com.cy.ppj.model.dto.order.OrderAddDTO;
import com.cy.ppj.model.dto.order.OrderDefaultPropertiesDTO;
import com.cy.ppj.model.dto.order.OrderImportDTO;
import com.cy.ppj.model.dto.order.ToDayLoanSuccessOrderCountDTO;
import com.cy.ppj.model.enums.ApplyStatus;
import com.cy.ppj.model.enums.AuditResult;
import com.cy.ppj.model.enums.CommissionStatus;
import com.cy.ppj.model.enums.OrderRejectType;
import com.cy.ppj.model.enums.OrderStatus;
import com.cy.ppj.model.enums.Process;
import com.cy.ppj.model.enums.RepayType;
import com.cy.ppj.model.enums.account.BrokerLevel;
import com.cy.ppj.model.enums.customer.CustomerImageType;
import com.cy.ppj.model.enums.order.OrderImageType;
import com.cy.ppj.model.enums.OrderWithholdStatus;
import com.cy.ppj.model.query.OrderAdminByTypeQuery;
import com.cy.ppj.model.query.OrderAdminQuery;
import com.cy.ppj.model.query.OrderQuery;
import com.cy.ppj.model.vo.OrderAdminByTypeVO;
import com.cy.ppj.model.vo.OrderAdminVO;
import com.cy.ppj.model.vo.OrderDetailAdminVO;
import com.cy.ppj.model.vo.OrderDetailVO;
import com.cy.ppj.model.vo.OrderProcessVO;
import com.cy.ppj.model.vo.OrderScanRecordDetailVO;
import com.cy.ppj.model.vo.OrderVO;
import com.cy.ppj.service.BaseService;
import com.cy.ppj.service.order.OrderService;
import com.cy.ppj.service.product.ProductService;


/**
 * 订单业务接口实现类
 *
 * @author: tanyilin
 * @create: 2018年7月20日 下午9:31:14
 */
@Slf4j
@Service
public class OrderServiceImpl extends BaseService implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderExtMapper orderExtMapper;
    @Autowired
    private OrderWithholdMapper orderWithholdMapper;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private CustomerContactMapper customerContactMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private OrderAuditRecordMapper orderAuditRecordMapper;
    @Autowired
    private ProductService productService;
    @Autowired
    private OrderManagerMapper orderUserMapper;
    @Autowired
    private ProductRateMapper productRateMapper;
    @Autowired
    private ManagerMapper managerMapper;
    @Autowired
    private StatisticsService statisticsService;
    @Autowired
    private UserOrderInfoMapper userOrderInfoMapper;
    @Autowired
    private BrokerService        brokerService;
    @Autowired
    private UserInfoMapper       userInfoMapper;
    @Autowired
	private CommissionService    commissionService;
    @Autowired
    private UserMapper           userMapper;
    @Autowired
	private CertificationService certificationService;
    @Autowired
    private OrderImageMapper     orderImageMapper;
    @Autowired
    private FileService          fileService;
    @Autowired
    private CustomerImageMapper  customerImageMapper;
    @Autowired
    private DictService          dictService;
    
    @Override
    @Transactional
    public Result addOrder(OrderAddDTO orderAddDTO) {

    	//验证经纪人是否已实名认证
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(orderAddDTO.getUserId());
        userInfo = userInfoMapper.selectOne(userInfo);
        state(userInfo != null, "经纪人请先进行实名认证");
        
        //对客户进行实名认证
        Result<Map<String, String>> certificationResult = certificationService.certificationIdCard(orderAddDTO.getName(), orderAddDTO.getIdNo());
        state(certificationResult.isOk(), certificationResult.getMessage());
        
        //订单基本信息
        Date now = new Date();
        Long orderId = 0L;
        OrderStatus orderStatus = orderAddDTO.getOrderStatus();
        Order order = new Order();
        BeanUtils.copyProperties(orderAddDTO, order);
        order.setCityId(userInfo.getCityId());
        // 根据产品查询相应的期限、利率、金额、还款方式等
        OrderDefaultPropertiesDTO odpDto = productMapper.selectOrderDefaultProperties(orderAddDTO.getProductId(), null);
        state(odpDto != null, "获取产品信息异常");
        if (order.getLoanAmount() != null && order.getPeriods() != null) {
            // 如果页面传进来的 借款金额和期限都不为空，则根据产品ID和期限去确定还款方式、利率
            ProductRate pr = productRateMapper.queryRateByProductIdAndPeriods(orderAddDTO.getProductId(), orderAddDTO.getPeriods());
            state(pr != null, "获取产品信息异常");
            order.setRate(pr.getRate());
            order.setRepayType(pr.getRepayType());
        } else {
            //如果为空，则使用默认值
            BeanUtils.copyProperties(odpDto, order);
        }
        //借款金额转成元为单位
        if (order.getLoanAmount() != null) {
            order.setLoanAmount(order.getLoanAmount().multiply(new BigDecimal(10000)));
        }
        order.setApplyStatus(ApplyStatus.PROCESSING);
        order.setOrderStatus(orderStatus);
        order.setCreateTime(now);
        order.setUpdateTime(now);
        //根据身份证号码查询客户，存在就设置客户ID，不存在就新增一个客户,并设置新客户的ID
        Customer customer = new Customer();
        customer.setIdNo(orderAddDTO.getIdNo());
        Customer dbCustomer = customerMapper.selectOne(customer);
        if (dbCustomer == null) {
            customer.setName(orderAddDTO.getName());
            customer.setSex(CommonUtils.getSexByIdNo(orderAddDTO.getIdNo()));
            customer.setMobile(orderAddDTO.getMobile());
            customer.setPassword(CommonUtils.md5Passwod(Constants.USER_INIT_PASSWORD));
            customer.setSource(Constants.CUSTOMER_SOURCE_PPJ);
            customer.setCreateTime(now);
            customer.setUpdateTime(now);
            customerMapper.insertSelective(customer);
            order.setCustomerId(customer.getId());
        } else {
            order.setCustomerId(dbCustomer.getId());
        }
        //设置订单的代扣、佣金发放初始状态
        if (odpDto.getUseWithhold()) {
            //如果该产品需要代扣
            order.setWithholdStatus(OrderWithholdStatus.WITHHOLD_WAIT);
        } else {
            order.setWithholdStatus(OrderWithholdStatus.UN_NEED);
        }
        if (odpDto.getUseCommission()) {
            //如果需要返佣
            order.setCommissionStatus(CommissionStatus.PAY_WAIT);
        } else {
            order.setCommissionStatus(CommissionStatus.UN_NEED);
        }
        //添加订单
        orderMapper.insertSelective(order);
        orderId = order.getId();
        
        //添加第一条审核数据类型，‘申请成功’
        if(OrderStatus.APPLY_SUCCESS.equals(orderStatus)) {
        	
        	OrderAuditRecord orderAuditRecord = new OrderAuditRecord();
        	orderAuditRecord.setOrderId(order.getId());
        	orderAuditRecord.setProcess(Process.APPLY);
        	orderAuditRecord.setResult(AuditResult.PASS);
        	orderAuditRecord.setRemark("通过");
        	orderAuditRecord.setManagerId(0L);
        	orderAuditRecord.setCreateTime(now);
        	orderAuditRecord.setUpdateTime(now);
        	orderAuditRecordMapper.insertSelective(orderAuditRecord);
        }

        //维护用户数据
        UserOrderInfo userOrderInfo = new UserOrderInfo();
        userOrderInfo.setUserId(order.getUserId());
        userOrderInfo.setOrderCount(1);
        userOrderInfo.setOrderLoanCount(0);
        userOrderInfo.setLoanAmount(BigDecimal.ZERO);
        userOrderInfo.setCreateTime(now);
        userOrderInfoMapper.addUserOrderInfo(userOrderInfo);
        
        if (!odpDto.getUseWithhold() && !odpDto.getUseCommission()) {
            //如果不需要代扣，也不需要返佣，则不设置代扣参数
            return Result.success("新增订单成功", orderId);
        }
        BigDecimal brokerRate = BigDecimal.ZERO;
//        if(userInfo.getNewUser()) {
//        	// 如果经纪人是新用户，处于3个月体验期（钻石经纪人），则佣金率应该按照钻石的来
//        	brokerRate = brokerService.queryBrokerRate(BrokerLevel.DIAMOND);
//        }else {
//        	brokerRate = brokerService.queryBrokerRate(userInfo.getLevel());
//        }
        OrderWithhold orderWithhold = new OrderWithhold();
        orderWithhold.setOrderId(order.getId());
        orderWithhold.setWithholdRate(odpDto.getUseWithhold() ? odpDto.getWithholdRate() : BigDecimal.ZERO);
		orderWithhold.setCommissionRate(odpDto.getUseCommission() ? odpDto.getCommissionRate() : BigDecimal.ZERO);
        orderWithhold.setBrokerRate(brokerRate);
		orderWithhold.setCreateTime(now);
        orderWithholdMapper.insertSelective(orderWithhold);

        return Result.success("新增订单成功", orderId);
    }

    @Override
    @Transactional
    public void updateOrder(Order order) {
        order.setUpdateTime(new Date());
        orderMapper.updateByPrimaryKeySelective(order);
    }

    @Override
    @Transactional
    public void orderLoanSuccess(Order order, Long managerId) {
        Order dbOrder = orderMapper.selectByPrimaryKey(order.getId());
        state(dbOrder != null, "订单不存在");
        ProductRate productRate = productRateMapper.queryRateByProductIdAndPeriods(dbOrder.getProductId(), order.getPeriods());
        state(productRate != null, "该订单的产品利率异常");
        order.setRate(productRate.getRate());
        order.setRepayType(productRate.getRepayType());
        order.setUpdateTime(new Date());
        orderMapper.updateByPrimaryKeySelective(order);
        OrderAuditAO orderAuditAO = new OrderAuditAO();
        orderAuditAO.setId(order.getId());
        orderAuditAO.setIsPass(true);
        orderAuditAO.setRemark("放款成功");
        auditOrder(orderAuditAO, managerId);
    }

    @Override
    @Transactional
    public void auditOrder(OrderAuditAO orderAuditAO, Long managerId) {
        Date now = new Date();
        //获取订单
        Order order = new Order();
        order.setId(orderAuditAO.getId());
        order.setOrderStatus(orderAuditAO.getOrderStatus());
        order = orderMapper.selectOne(order);
        state(order != null, "订单不存在");
        //当前流程审核是否通过
        boolean isPass = orderAuditAO.getIsPass();
        OrderAuditRecord orderAuditRecord = new OrderAuditRecord();
        doAudit(order, orderAuditRecord, isPass);
        //更新订单状态
        order.setUpdateTime(now);
        boolean isLoan = order.getOrderStatus().equals(OrderStatus.LOAN_SUCCESS);
        if (isLoan) {
            order.setLoanTime(now);
        }
        if(!isPass) {
        	// 如果审核结果是拒绝，更新拒绝类型、拒绝原因
        	order.setRejectType(orderAuditAO.getRejectType());
        	order.setRejectReason(orderAuditAO.getRemark());
        }
        orderMapper.updateByPrimaryKeySelective(order);
        //新增审核记录数据
        orderAuditRecord.setRemark(orderAuditAO.getRemark());
        orderAuditRecord.setOrderId(order.getId());
        orderAuditRecord.setManagerId(managerId);
        orderAuditRecord.setCreateTime(now);
        orderAuditRecordMapper.insertSelective(orderAuditRecord);

        if (isLoan && !CommonUtils.isEmpty(order.getUserId()) && order.getUserId().longValue() > 0) {
            //放款成功记录数据
            StatisticsUserLoanAmountDTO statisticsUserLoanAmount = new StatisticsUserLoanAmountDTO();
            statisticsUserLoanAmount.setUserId(order.getUserId());
            statisticsUserLoanAmount.setLoanAmount(order.getLoanAmount());
            statisticsUserLoanAmount.setTime(now);
            statisticsService.addStatisticsUserLoanAmount(statisticsUserLoanAmount);
            //经纪人等级升级
            //brokerService.upgradeBrokerLevel(order.getUserId(), now);
            // 放款成功自动发放佣金（处于待发放状态的订单）
            if(CommissionStatus.PAY_WAIT.equals(order.getCommissionStatus())) {
            	// 查询该笔订单的经纪人
            	UserInfo userInfo = new UserInfo();
                userInfo.setUserId(order.getUserId());
                userInfo = userInfoMapper.selectOne(userInfo);
                // 查询该笔订单的客户
                Customer customer = customerMapper.selectByPrimaryKey(order.getCustomerId());
                if(userInfo != null && customer != null) {
                	if(!customer.getIdNo().equals(userInfo.getIdNo())) {
                		commissionService.payCommission2(order.getId());
                	}
                }
                
            }
        }

    }

    /**
     * 进行订单审核逻辑判断
     * 
     * @param order
     * @param orderAuditRecord
     * @param isPass
     */
    private void doAudit(Order order, OrderAuditRecord orderAuditRecord, boolean isPass) {
        //产品ID
        Long productId = order.getProductId();
        //获取产品绑定的审核流程
        List<Process> processes = productService.getProcessByProductIdInCache(productId);
        //如果是电核失败,流程中又有复议
        if (OrderStatus.CALL_VERIFY_FAIL.equals(order.getOrderStatus())
                && processes.stream().anyMatch(p -> p.equals(Process.REVIEW))) {
            //申请状态要变为‘处理中’，订单审核状态要变为‘复议中’
            order.setApplyStatus(ApplyStatus.PROCESSING);
            order.setOrderStatus(OrderStatus.REVIEW_WAIT);
            //设置审核记录数据
            orderAuditRecord.setProcess(Process.REVIEW_APPLY);
            orderAuditRecord.setResult(AuditResult.PASS);
            return;
        }
        if (OrderStatus.REVIEW_WAIT.equals(order.getOrderStatus())) {
            //等待复议-->复议结果
            ApplyStatus applyStatus = isPass ? ApplyStatus.PROCESSING : ApplyStatus.REJECT;
            OrderStatus orderStatus = isPass ? OrderStatus.REVIEW_SUCCESS : OrderStatus.REVIEW_FAIL;
            order.setApplyStatus(applyStatus);
            order.setOrderStatus(orderStatus);
            return;
        }
        //不是申请复议动作，则走正常审核逻辑
        state(ApplyStatus.PROCESSING.equals(order.getApplyStatus()), "订单审核状态异常");
        //订单处于“处理中”的时候,才能进行审核动作
        //当前订单状态
        OrderStatus orderStatus = order.getOrderStatus();
        //根据订单审核状态获取 上一步 审核流程
        Process preProcess = Process.getProcess(orderStatus);
        Process currentProcess = CommonUtils.getNextProcess(preProcess, processes);
        state(currentProcess != null, "流程已经结束");
        //判断新的审核状态
        OrderStatus newOrderStatus = isPass ? currentProcess.getPass() : currentProcess.getReject();
        order.setOrderStatus(newOrderStatus);
        //设置审核记录数据
        orderAuditRecord.setProcess(currentProcess);
        orderAuditRecord.setResult(isPass ? AuditResult.PASS : AuditResult.REJECT);
        if (!isPass) {
            order.setApplyStatus(ApplyStatus.REJECT);
            return;
        }
        if (processes.stream().noneMatch(p -> p.getOrder().compareTo(currentProcess.getOrder()) > 0)
                || OrderStatus.LOAN_SUCCESS.equals(newOrderStatus)) {
            //如果没有下一步，就直接pass
            order.setApplyStatus(ApplyStatus.PASS);
        }
    }

    @Override
    @Transactional
    public void setOrderWithhold(OrderWithholdSetAO orderWithholdSetAO) {

        //验证该订单是否存在
        Order order = new Order();
        order.setId(orderWithholdSetAO.getOrderId());
        order = orderMapper.selectOne(order);
        state(order != null, "该订单不存在");

        //更新客户姓名和身份证号码(如果有参数传进来)
        /*if (!StringUtils.isEmpty(orderWithholdSetAO.getCustomerName()) ||
                !StringUtils.isEmpty(orderWithholdSetAO.getIdNo())) {
            Customer updateCustomer = new Customer();
            updateCustomer.setId(order.getCustomerId());
            if (!StringUtils.isEmpty(orderWithholdSetAO.getCustomerName())) {
            	updateCustomer.setName(orderWithholdSetAO.getCustomerName());
            }
            if (!StringUtils.isEmpty(orderWithholdSetAO.getIdNo())) {
                Customer currentCustomer = customerMapper.selectByPrimaryKey(order.getCustomerId());
                if(!orderWithholdSetAO.getIdNo().equals(currentCustomer.getIdNo())) {
                	Customer dbCustomer = new Customer();
                	dbCustomer.setIdNo(orderWithholdSetAO.getIdNo());
                	dbCustomer = customerMapper.selectOne(dbCustomer);
                	state(dbCustomer == null, "该身份证号码已存在");
                	updateCustomer.setIdNo(orderWithholdSetAO.getIdNo());
                }
            }
            updateCustomer.setUpdateTime(new Date());
            int result = customerMapper.updateByPrimaryKeySelective(updateCustomer);
            state(result == 1, "设置订单代扣参数异常");
        }*/


        OrderWithhold orderWithhold = new OrderWithhold();
        BeanUtils.copyProperties(orderWithholdSetAO, orderWithhold);

        //设置代扣参数
        OrderWithhold dbOrderWithhold = new OrderWithhold();
        dbOrderWithhold.setOrderId(orderWithholdSetAO.getOrderId());
        dbOrderWithhold = orderWithholdMapper.selectOne(dbOrderWithhold);

        if (dbOrderWithhold == null) {
            orderWithhold.setCreateTime(new Date());
            orderWithholdMapper.insertSelective(orderWithhold);
        } else {
            orderWithhold.setId(dbOrderWithhold.getId());
            orderWithhold.setUpdateTime(new Date());
            orderWithholdMapper.updateByPrimaryKeySelective(orderWithhold);
        }
    }

    @Override
    @Transactional
    public void setOrderExt(OrderExtSetAO orderExtSetAO) {
        //先删除原有的
        OrderExt orderExt = new OrderExt();
        orderExt.setOrderId(orderExtSetAO.getOrderId());
        int result = orderExtMapper.delete(orderExt);
        state(result == 1, "设置外部单号异常");
        //再新增
        orderExt.setExtNo(orderExtSetAO.getExtNo());
        orderExt.setCreateTime(new Date());
        orderExtMapper.insertSelective(orderExt);
    }

    @Override
    public PageBean<OrderVO> queryOrderList(OrderQuery orderQuery) {
        int total = orderMapper.queryOrderListCount(orderQuery);
        List<OrderVO> list = new ArrayList<>();
        if (total > 0) {
            orderQuery.startPage();
            list = orderMapper.queryOrderList(orderQuery);
            list.stream().filter(o -> o.getCommissionRate() != null).forEach(o -> {
                BigDecimal commission = CommonUtils.multiplyWithPercent(o.getLoanAmount(), o.getCommissionRate());
                commission = CommonUtils.multiplyWithPercent(commission, o.getBrokerRate());
                o.setBrokerCommission(commission);
            });
        }
        return new PageBean<>(list, total);
    }

    @Override
    public OrderDetailVO orderDetail(Long orderId) {
        OrderDetailVO orderDetailVO = orderMapper.queryOrderDetail(orderId);
        state(orderDetailVO != null, "该订单不存在");
        orderDetailVO.setCustomerIdNo(CommonUtils.idNoFormat(orderDetailVO.getCustomerIdNo(), 4, 4));
        orderDetailVO.setCustomerMobile(CommonUtils.idNoFormat(orderDetailVO.getCustomerMobile(), 3, 4));
        //计算经纪人佣金
        if (orderDetailVO.getCommissionRate() != null) {
            BigDecimal commission = CommonUtils.multiplyWithPercent(orderDetailVO.getLoanAmount(), orderDetailVO.getCommissionRate());
            commission = CommonUtils.multiplyWithPercent(commission, orderDetailVO.getBrokerRate());
            orderDetailVO.setBrokerCommission(commission);
        } else {
            orderDetailVO.setBrokerCommission(BigDecimal.ZERO);
        }
        ApplyStatus applyStatus = orderDetailVO.getApplyStatus();
        OrderStatus orderStatus = orderDetailVO.getOrderStatus();
        // 判断该订单是否已被拒绝
        if(ApplyStatus.REJECT.equals(applyStatus)) {
        	orderDetailVO.setRejectTypeRemark(orderDetailVO.getRejectType().getRemark());
        }else {
        	orderDetailVO.setRejectType(null);
        }
        
        //找出订单当前流程
        //根据产品id获取产品绑定的审核流程
        List<Process> processes = productService.getProcessByProductIdInCache(orderDetailVO.getProductId());
        //定义当前流程
        Process currentProcess = CommonUtils.getCurrentProcess(processes, applyStatus, orderStatus);
        orderDetailVO.setCurrentProcess(currentProcess);
        //审核流程进度
        List<OrderProcessVO> dbOrderProcessList = orderMapper.queryOrderProcess(orderId, processes);
        List<OrderProcessVO> orderProcessList = new ArrayList<>();
        processes.stream().forEach(p -> {
            Optional<OrderProcessVO> optional =
                    dbOrderProcessList.stream().filter(db -> p.equals(db.getProcess())).findFirst();
            if (optional.isPresent()) {
                orderProcessList.add(optional.get());
            } else if (!p.equals(Process.REVIEW)) {
                OrderProcessVO orderProcessVO = new OrderProcessVO();
                orderProcessVO.setProcess(p);
                orderProcessList.add(orderProcessVO);
            }
        });
        //按时间排序
        //List<OrderProcessVO> result = orderProcessList.stream().sorted(Comparator.comparing(OrderProcessVO::getAuditTime)).collect(Collectors.toList());
        orderDetailVO.setOrderProcessList(orderProcessList);
        return orderDetailVO;
    }

    @Override
    @Transactional
    public void assignUser(Long orderId, Long managerId) {
        //验证管理员是否审核员角色
        Manager manager = new Manager();
        manager.setId(managerId);
        manager = managerMapper.selectOne(manager);
        state(manager != null, "审核员不存在");
        boolean flag = Constants.AUDIT_ROLE_ID.equals(manager.getRoleId());
        state(flag, "该管理员用户不是审核员");

        //先根据订单id，删除原有的分配信息
        OrderManager record = new OrderManager();
        record.setOrderId(orderId);
        orderUserMapper.delete(record);
        //进行分配
        OrderManager orderUser = new OrderManager();
        orderUser.setOrderId(orderId);
        orderUser.setManagerId(managerId);
        orderUser.setCreateTime(new Date());
        orderUserMapper.insertSelective(orderUser);
    }

    @Override
    public PageBean<OrderAdminVO> queryOrderAdminList(OrderAdminQuery orderAdminQuery) {

        orderAdminQuery.setProductIdsList(dictService.selectProductIdsListInCache());

        int total = orderMapper.queryOrderAdminListCount(orderAdminQuery);
        List<OrderAdminVO> list = new ArrayList<>();
        if (total > 0) {
            orderAdminQuery.startPage();
            list = orderMapper.queryOrderAdminList(orderAdminQuery);
            list.stream().forEach(o -> {
                if (orderAdminQuery.getType() == 2 || orderAdminQuery.getType() == 3) {
                    //如果查询列表是未分配、已分配列表，需要对身份证号码进行脱敏
                    String idNo = o.getIdNo();
                    o.setIdNo(CommonUtils.idNoFormat(idNo, 4, 4));
                }
                //根据产品id获取产品绑定的审核流程
                List<Process> processes = o.getProcesses();
                //是否可以复议
                o.setHaveReviewProcess(processes.stream().anyMatch(p -> p.equals(Process.REVIEW)));
                if (ApplyStatus.REJECT.equals(o.getApplyStatus())) {
                    Process currentProcess = Process.getProcessByFailStatus(o.getOrderStatus());
                    o.setProcess(currentProcess);
                    o.setProcessRemark(currentProcess.getRemark());
                    return;
                }
                if (OrderStatus.REVIEW_WAIT.equals(o.getOrderStatus())) {
                    o.setProcess(Process.REVIEW);
                    o.setProcessRemark(Process.REVIEW.getRemark());
                    return;
                }
                //找到当前流程
                Process process = Process.getProcess(o.getOrderStatus());
                if (!ApplyStatus.PASS.equals(o.getApplyStatus())) {
                    //不为通过，寻找下一个流程
                    process = CommonUtils.getNextProcess(process, processes);
                }
                o.setProcess(process);
                o.setProcessRemark(process.getRemark());
            });

        }
        return new PageBean<>(list, total);
    }

    @Override
    public PageBean<OrderAdminByTypeVO> queryOrderAdminByType(OrderAdminByTypeQuery query) {
        int total = orderMapper.queryOrderAdminByTypeCount(query);
        List<OrderAdminByTypeVO> list = new ArrayList<>();
        if (total > 0) {
            query.startPage();
            list = orderMapper.queryOrderAdminByType(query);
        }
        return new PageBean<>(list, total);
    }

    @Override
    public PageBean<OrderWithholdAdminVO> queryOrderWithholdAdminList(OrderWithholdAdminQuery query) {

        int total = orderWithholdMapper.selectOrderWithholdAdminCount(query);
        List<OrderWithholdAdminVO> list = new ArrayList<>();
        if (total > 0) {
            query.startPage();
            list = orderWithholdMapper.selectOrderWithholdAdminList(query);
            //计算代扣金额
            list.stream().forEach(o -> {
                if (o.getLoanAmount() == null || BigDecimal.ZERO.compareTo(o.getLoanAmount()) >= 0) {
                    return;
                }
                if (o.getWithholdRate() != null) {
                    BigDecimal withholdAmount = o.getLoanAmount().multiply(o.getWithholdRate())
                            .divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
                    o.setWithholdAmount(withholdAmount);
                }

                if (o.getCommissionRate() != null) {
                    BigDecimal commissionAmount = o.getLoanAmount().multiply(o.getCommissionRate())
                            .divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
                    o.setCommissionAmount(commissionAmount);
                }
            });

        }

        return new PageBean<>(list, total);
    }

	@Override
	public PageBean<OrderScanRecordAdminVO> selectOrderScanRecordAdmin(OrderScanRecordAdminQuery query) {
		int total = orderMapper.selectOrderScanRecordAdminCount(query);
		List<OrderScanRecordAdminVO> list = new ArrayList<>();
		if(total > 0) {
			query.startPage();
			list = orderMapper.selectOrderScanRecordAdminList(query);
			list.stream().forEach(o -> {
				o.setSalesName(StringUtils.isEmpty(o.getU2SalesName()) ? StringUtils.isEmpty(o.getU1SalesName()) ? " " : o.getU1SalesName() : o.getU2SalesName());
				o.setU1SalesName(null);
				o.setU2SalesName(null);
				//手机号码脱敏
				String mobile = o.getMobile();
				if(!StringUtils.isEmpty(mobile)) {
					if(mobile.length() == 11) {
						String prefix3 = mobile.substring(0, 3);
                        String suffix4 = mobile.substring(mobile.length() - 4);
                        o.setMobile(prefix3 + "****" + suffix4);
					}
				}
				//身份证号码脱敏
				String idNo = o.getIdNo();
                if(!StringUtils.isEmpty(idNo)) {
                    if (idNo.length() >= 15) {
                        String prefix4 = idNo.substring(0, 4);
                        String suffix4 = idNo.substring(idNo.length() - 4);
                        o.setIdNo(prefix4 + "****" + suffix4);
                    }
                }
			});
		}
		return new PageBean<>(list, total);
	}

	@Override
	@Transactional
	public void doConfirmOrReturnOrderScanRecord(Long orderId, OrderStatus orderStatus, Long managerId) {
		Order dbOrder = new Order();
		dbOrder.setId(orderId);
		dbOrder.setOrderStatus(OrderStatus.APPLY);
		dbOrder = orderMapper.selectOne(dbOrder);
		state(dbOrder != null, "订单浏览记录状态异常");
		
		Date now = new Date();
		//更新订单状态
        Order order = new Order();
        order.setId(orderId);
        order.setOrderStatus(orderStatus);
        if(OrderStatus.APPLY_FAIL.equals(orderStatus)) {
        	order.setApplyStatus(ApplyStatus.REJECT);
        }
        order.setUpdateTime(now);
        orderMapper.updateByPrimaryKeySelective(order);
        
        //生成第一条订单审核记录数据
        OrderAuditRecord orderAuditRecord = new OrderAuditRecord();
    	orderAuditRecord.setOrderId(orderId);
    	orderAuditRecord.setProcess(Process.APPLY);
    	if(OrderStatus.APPLY_SUCCESS.equals(orderStatus)) {
    		
    		orderAuditRecord.setResult(AuditResult.PASS);
    		orderAuditRecord.setRemark("确认订单浏览记录,申请提交成功");
    	}else if(OrderStatus.APPLY_FAIL.equals(orderStatus)) {
    		
    		orderAuditRecord.setResult(AuditResult.REJECT);
    		orderAuditRecord.setRemark("退回订单浏览记录");
    	}
    	orderAuditRecord.setManagerId(managerId);
    	orderAuditRecord.setCreateTime(now);
    	orderAuditRecordMapper.insertSelective(orderAuditRecord);
		
	}

	@Override
	public PageBean<OrderScanRecordVO> selectOrderScanRecord(OrderScanRecordQuery query) {
		int total = orderMapper.selectOrderScanRecordCount(query);
		List<OrderScanRecordVO> list = new ArrayList<>();
		if(total > 0) {
			query.startPage();
			list = orderMapper.selectOrderScanRecordList(query);
		}
		return new PageBean<>(list, total);
	}

	@Override
	public OrderScanRecordDetailVO selectOrderScanRecordDetail(Long orderId) {
		OrderScanRecordDetailVO orderScanRecordDetailVO = orderMapper.selectOrderScanRecordDetail(orderId);
		state(orderScanRecordDetailVO != null, "订单浏览记录数据异常");
		// 计算经纪人累计返佣
        if (orderScanRecordDetailVO.getCommissionRate() != null) {
            BigDecimal commission = CommonUtils.multiplyWithPercent(orderScanRecordDetailVO.getLoanAmount(), orderScanRecordDetailVO.getCommissionRate());
            commission = CommonUtils.multiplyWithPercent(commission, orderScanRecordDetailVO.getBrokerRate());
            orderScanRecordDetailVO.setBrokerCommission(commission);
        } else {
        	orderScanRecordDetailVO.setBrokerCommission(BigDecimal.ZERO);
        }
		return orderScanRecordDetailVO;
	}

	@Override
	@Transactional
	public void doConfirmOrderScanRecord(OrderScanRecordComfirmAO orderScanRecordComfirmAO) {
		Order dbOrder = new Order();
		dbOrder.setId(orderScanRecordComfirmAO.getOrderId());
		dbOrder = orderMapper.selectOne(dbOrder);
		state(dbOrder != null , "数据异常，请刷新重新操作");
		
		Order updateOrder = new Order();
		updateOrder.setId(dbOrder.getId());
		updateOrder.setMobile(orderScanRecordComfirmAO.getCustomerMobile());
		orderMapper.updateByPrimaryKeySelective(updateOrder);
		
		Long customerId = dbOrder.getCustomerId();
		Customer dbCustomer = new Customer();
		dbCustomer.setId(customerId);
		dbCustomer = customerMapper.selectOne(dbCustomer);
		state(dbCustomer != null , "数据异常，请刷新重新操作");
		
		if(!dbCustomer.getIdNo().equals(orderScanRecordComfirmAO.getCustomerIdNo()) || 
				!dbCustomer.getName().equals(orderScanRecordComfirmAO.getCustomerName())) {
			
			Customer updateCustomer = new Customer();
			updateCustomer.setId(customerId);
			updateCustomer.setName(orderScanRecordComfirmAO.getCustomerName());
			if(!dbCustomer.getIdNo().equals(orderScanRecordComfirmAO.getCustomerIdNo())) {
				Customer newCustomer = new Customer();
				newCustomer.setIdNo(orderScanRecordComfirmAO.getCustomerIdNo());
				newCustomer = customerMapper.selectOne(newCustomer);
				state(newCustomer == null, "该身份证号码已存在");
				
				updateCustomer.setIdNo(orderScanRecordComfirmAO.getCustomerIdNo());
			}
			customerMapper.updateByPrimaryKeySelective(updateCustomer);
			
		}
		
		
		this.doConfirmOrReturnOrderScanRecord(orderScanRecordComfirmAO.getOrderId(), OrderStatus.APPLY_SUCCESS, 0L);
	}

	@Override
	public PageBean<OrderAdminVO> selectAllOrderAdminList(OrderAdminQuery query) {

        query.setProductIdsList(dictService.selectProductIdsListInCache());

		int total = orderMapper.selectAllOrderAdminListCount(query);
		List<OrderAdminVO> list = new ArrayList<>();
		if(total > 0) {
			query.startPage();
			list = orderMapper.selectAllOrderAdminList(query);
			list.stream().forEach(o -> {
				if(o.getOrderStatus() != null) {
					o.setOrderStatusText(o.getOrderStatus().getText());
				}
				o.setSalesName(StringUtils.isEmpty(o.getU2SalesName()) ? StringUtils.isEmpty(o.getU1SalesName()) ? " " : o.getU1SalesName() : o.getU2SalesName());
				o.setU1SalesName(null);
				o.setU2SalesName(null);
				o.setWithholdRateText(StringUtils.isEmpty(o.getWithholdRate()) ? " " : String.valueOf(o.getWithholdRate()).concat("%"));
				o.setCommissionRateText(StringUtils.isEmpty(o.getCommissionRate()) ? " " : String.valueOf(o.getCommissionRate()).concat("%"));
			});
		}
		return new PageBean<>(list, total);
	}

	@Override
	public PageBean<OrderAdminVO> selectUnassignedOrderAdminList(OrderAdminQuery query) {

        query.setProductIdsList(dictService.selectProductIdsListInCache());

		int total = orderMapper.selectUnassignedOrderAdminListCount(query);
		List<OrderAdminVO> list = new ArrayList<>();
		if(total > 0) {
			query.startPage();
			list = orderMapper.selectUnassignedOrderAdminList(query);
			list.stream().forEach(o -> {
				//身份证号码脱敏
                String idNo = o.getIdNo();
                o.setIdNo(CommonUtils.idNoFormat(idNo, 4, 4));
                if(o.getOrderStatus() != null) {
					o.setOrderStatusText(o.getOrderStatus().getText());
				}
                o.setSalesName(StringUtils.isEmpty(o.getU2SalesName()) ? StringUtils.isEmpty(o.getU1SalesName()) ? " " : o.getU1SalesName() : o.getU2SalesName());
				o.setU1SalesName(null);
				o.setU2SalesName(null);
			});
		}
		return new PageBean<>(list, total);
	}

	@Override
	public PageBean<OrderAdminVO> selectProcessingOrderAdminList(OrderAdminQuery query) {

        query.setProductIdsList(dictService.selectProductIdsListInCache());

		int total = orderMapper.selectProcessingOrderAdminListCount(query);
		List<OrderAdminVO> list = new ArrayList<>();
		if(total > 0) {
			query.startPage();
			list = orderMapper.selectProcessingOrderAdminList(query);
			list.stream().forEach(o -> {
				if(o.getOrderStatus() != null) {
					o.setOrderStatusText(o.getOrderStatus().getText());
				}
				o.setSalesName(StringUtils.isEmpty(o.getU2SalesName()) ? StringUtils.isEmpty(o.getU1SalesName()) ? " " : o.getU1SalesName() : o.getU2SalesName());
				o.setU1SalesName(null);
				o.setU2SalesName(null);
				//身份证号码脱敏
                String idNo = o.getIdNo();
                o.setIdNo(CommonUtils.idNoFormat(idNo, 4, 4));
                //根据产品id获取产品绑定的审核流程
                List<Process> processes = o.getProcesses();
                //是否可以复议
                o.setHaveReviewProcess(processes.stream().anyMatch(p -> p.equals(Process.REVIEW)));
                if (ApplyStatus.REJECT.equals(o.getApplyStatus())) {
                    Process currentProcess = Process.getProcessByFailStatus(o.getOrderStatus());
                    o.setProcess(currentProcess);
                    o.setProcessRemark(currentProcess.getRemark());
                    return;
                }
                if (OrderStatus.REVIEW_WAIT.equals(o.getOrderStatus())) {
                    o.setProcess(Process.REVIEW);
                    o.setProcessRemark(Process.REVIEW.getRemark());
                    return;
                }
                //找到当前流程
                Process process = Process.getProcess(o.getOrderStatus());
                if (!ApplyStatus.PASS.equals(o.getApplyStatus())) {
                    //不为通过，寻找下一个流程
                    process = CommonUtils.getNextProcess(process, processes);
                }
                o.setProcess(process);
                o.setProcessRemark(process.getRemark());
            });
		}
		return new PageBean<>(list, total);
	}

	@Override
	public PageBean<OrderAdminVO> selectPassOrderAdminList(OrderAdminQuery query) {

        query.setProductIdsList(dictService.selectProductIdsListInCache());

		int total = orderMapper.selectPassOrderAdminListCount(query);
		List<OrderAdminVO> list = new ArrayList<>();
		if(total > 0) {
			query.startPage();
			list = orderMapper.selectPassOrderAdminList(query);
			list.stream().forEach(o -> {
				//身份证号码脱敏
                String idNo = o.getIdNo();
                o.setIdNo(CommonUtils.idNoFormat(idNo, 4, 4));
                if(o.getOrderStatus() != null) {
					o.setOrderStatusText(o.getOrderStatus().getText());
				}
                o.setSalesName(StringUtils.isEmpty(o.getU2SalesName()) ? StringUtils.isEmpty(o.getU1SalesName()) ? " " : o.getU1SalesName() : o.getU2SalesName());
				o.setU1SalesName(null);
				o.setU2SalesName(null);
			});
		}
		return new PageBean<>(list, total);
	}

	@Override
	public PageBean<OrderAdminVO> selectRejectOrderAdminList(OrderAdminQuery query) {

        query.setProductIdsList(dictService.selectProductIdsListInCache());

		int total = orderMapper.selectRejectOrderAdminListCount(query);
		List<OrderAdminVO> list = new ArrayList<>();
		if(total > 0) {
			query.startPage();
			list = orderMapper.selectRejectOrderAdminList(query);
			list.stream().forEach(o -> {
				//身份证号码脱敏
                String idNo = o.getIdNo();
                o.setIdNo(CommonUtils.idNoFormat(idNo, 4, 4));
                o.setRejectTypeRemark(o.getRejectType().getRemark());
                if(o.getOrderStatus() != null) {
					o.setOrderStatusText(o.getOrderStatus().getText());
				}
                o.setSalesName(StringUtils.isEmpty(o.getU2SalesName()) ? StringUtils.isEmpty(o.getU1SalesName()) ? " " : o.getU1SalesName() : o.getU2SalesName());
				o.setU1SalesName(null);
				o.setU2SalesName(null);
			});
		}
		return new PageBean<>(list, total);
	}

	@Override
	public int selectToDayApplyOrderCount(OrderCountQuery query) {
		int count = orderMapper.selectToDayApplyOrderCount(query);
		return count;
	}

	@Override
	public ToDayLoanSuccessOrderCountDTO selectToDayLoanSuccessOrderCount(OrderCountQuery query) {
		ToDayLoanSuccessOrderCountDTO dto = orderMapper.selectToDayLoanSuccessOrderCount(query);
		return dto;
	}

	@Override
	public int selectToDayRejectOrderCount(OrderCountQuery query) {
		int count = orderMapper.selectToDayRejectOrderCount(query);
		return count;
	}

	@Override
	public CustomerOrderDTO selectCustomerOrderDTO(String idNo, Long productId) {
		CustomerOrderDTO customerOrderDTO = customerMapper.selectCustomerOrderInfo(idNo, productId);
		return customerOrderDTO;
	}

	@Override
	public CustomerOrderScanRecordDTO selectCustomerOrderScanRecordDTO(String idNo, Long productId) {
		CustomerOrderScanRecordDTO customerOrderScanRecordDTO = customerMapper.selectCustomerOrderScanRecordInfo(idNo, productId);
		return customerOrderScanRecordDTO;
	}

	@Override
	public List<OrderImportDTO> getOrderImportDTO(MultipartFile file) {
		
		Workbook wb = null;
		
		try {
            if (CommonUtils.isExcel2003(file.getOriginalFilename())) {
                wb = new HSSFWorkbook(file.getInputStream());
            } else {
                wb = new XSSFWorkbook(file.getInputStream());
            }
        } catch (IOException e) {
            log.error("improtExcel error:", e);
            throw new MsgException("读取Excel文件异常");
        }
		
		List<OrderImportDTO> list = new ArrayList<>();
		
		Sheet sheet = wb.getSheetAt(0);
		log.info("表格长度==============》{}", sheet.getLastRowNum());
		for(int i = 1; i <= sheet.getLastRowNum(); i++) {
			Row row = sheet.getRow(i);
			
			String customerName = row.getCell(0) == null ? "" : row.getCell(0).getStringCellValue();
			String mobile = row.getCell(1) == null ? "" : new BigDecimal(row.getCell(1).getNumericCellValue()).toString();
			String idNo = row.getCell(2) == null ? "" : row.getCell(2).getStringCellValue();
			String productName = row.getCell(3) == null ? "" : row.getCell(3).getStringCellValue();
			
			int periods = row.getCell(4) == null ? 0 : (int) row.getCell(4).getNumericCellValue();
			BigDecimal loanAmount = row.getCell(5) == null ? BigDecimal.ZERO : new BigDecimal(row.getCell(5).getNumericCellValue()).setScale(2, RoundingMode.HALF_UP);
			
			Date createTime = row.getCell(6) == null ? null : row.getCell(6).getDateCellValue();
			Date loanTime = row.getCell(7) == null ? null : row.getCell(7).getDateCellValue();
			
			OrderImportDTO dto = new OrderImportDTO();
			dto.setCustomerName(customerName);
			dto.setMobile(mobile);
			dto.setIdNo(idNo);
			dto.setProductName(productName);
			dto.setPeriods(periods);
			dto.setLoanAmount(loanAmount);
			dto.setCreateTime(createTime);
			dto.setLoanTime(loanTime);
			
			list.add(dto);
		}
		
		return list;
	}

	@Override
	@Transactional
	public void importOrder(List<OrderImportDTO> orderImportList) {

		for(int i = 0; i < orderImportList.size(); i++) {
			OrderImportDTO dto = orderImportList.get(i);
			Long customerId = 0L;
			Long productId = 0L;
			
			//根据身份证号码查询客户，存在就设置客户ID，不存在就新增一个客户,并设置新客户的ID
	        Customer customer = new Customer();
	        customer.setIdNo(dto.getIdNo());
	        Customer dbCustomer = customerMapper.selectOne(customer);
	        if (dbCustomer == null) {
	            customer.setName(dto.getCustomerName());
	            customer.setSex(CommonUtils.getSexByIdNo(dto.getIdNo()));
	            customer.setMobile(dto.getMobile());
	            customer.setPassword(CommonUtils.md5Passwod(Constants.USER_INIT_PASSWORD));
	            customer.setSource(Constants.CUSTOMER_SOURCE_PPJ);
	            customer.setCreateTime(dto.getCreateTime());
	            customer.setUpdateTime(dto.getCreateTime());
	            customerMapper.insertSelective(customer);
	            
	            customerId = customer.getId();
	        } else {
	        	customerId = dbCustomer.getId();
	        }
	        
	        if("工行家装贷".equals(dto.getProductName())) {
	        	productId = 51L;
	        }else if("建行家装贷".equals(dto.getProductName())) {
	        	productId = 52L;
	        }
	        
	        Order order = new Order();
	        order.setCustomerId(customerId);
	        order.setProductId(productId);
	        order.setCityId(1L);
	        order.setMobile(dto.getMobile());
	        order.setPeriods(dto.getPeriods());
	        order.setLoanAmount(dto.getLoanAmount());
	        order.setRate(new BigDecimal("0.31"));
	        order.setRepayType(RepayType.DEBX);
	        order.setOrderStatus(OrderStatus.LOAN_SUCCESS);
	        order.setApplyStatus(ApplyStatus.PASS);
	        order.setUserId(0L);
	        order.setCommissionStatus(CommissionStatus.UN_NEED);
	        order.setWithholdStatus(OrderWithholdStatus.UN_NEED);
	        order.setCreateTime(dto.getCreateTime());
	        order.setUpdateTime(dto.getLoanTime());
	        order.setLoanTime(dto.getLoanTime());
	        order.setRejectType(OrderRejectType.UN_REJECT);
	        
	        //添加订单
	        orderMapper.insertSelective(order);
		}
	}

	@Override
	public PageBean<DecorationPassOrderListAdminVO> selectDecorationPassOrderListAdmin(
			DecorationPassOrderListAdminQuery query) {
		int total = orderMapper.selectDecorationPassOrderListAdminCount(query);
		List<DecorationPassOrderListAdminVO> list = new ArrayList<>();
		if(total > 0) {
			query.startPage();
			list = orderMapper.selectDecorationPassOrderListAdmin(query);
			list.stream().forEach(o -> {
				o.setIdNo(CommonUtils.idNoFormat(o.getIdNo(), 4, 4));
				o.setMobile(CommonUtils.idNoFormat(o.getMobile(), 3, 4));
			});
		}
		return new PageBean<>(list, total);
	}

	@Override
	@Transactional
	public void addOrder(OrderAdminAddAO addAO, Long managerId) {
		
		//业务员手机号码或者姓名
		UserInfo dbBrokerUserInfo = new UserInfo();
		String brokerMobile = addAO.getBrokerMobile().replace(" ", "");
		if(CommonUtils.isNumeric(brokerMobile)) {
			//如果是纯数字，则认为填写的是手机号码
			//验证业务员是否存在、是否已实名认证
			User brokerUser = new User();
			brokerUser.setMobile(addAO.getBrokerMobile());
			brokerUser = userMapper.selectOne(brokerUser);
			state(brokerUser != null, "保存订单失败，该业务员手机号码未注册");
			
			UserInfo queryBrokerUserInfo = new UserInfo();
			queryBrokerUserInfo.setUserId(brokerUser.getId());
			dbBrokerUserInfo = userInfoMapper.selectOne(queryBrokerUserInfo);
	        state(dbBrokerUserInfo != null, "保存订单失败，该业务员未进行实名认证");
	        
		}else {
			//否则，认为填写的是业务员姓名
			UserInfo queryBrokerUserInfo = new UserInfo();
			queryBrokerUserInfo.setRealName(brokerMobile);
			int count = userInfoMapper.selectCount(queryBrokerUserInfo);
			state(!(count >= 2), "系统业务员存在同名的情况，请改用填写业务员已注册的手机号码的方式录入");
			dbBrokerUserInfo = userInfoMapper.selectOne(queryBrokerUserInfo);
	        state(dbBrokerUserInfo != null, "保存订单失败，该业务员未进行实名认证");
			
		}
		
        //对客户进行实名认证
        Result<Map<String, String>> certificationResult = certificationService.certificationIdCard(addAO.getName(), addAO.getIdNo());
        state(certificationResult.isOk(), "客户".concat(certificationResult.getMessage()));
        
        //订单基本信息
        Date now = new Date();
        Long customerId = 0L;
        Order order = new Order();
        BeanUtils.copyProperties(addAO, order);
        
        //根据身份证号码查询客户，存在就设置客户ID，不存在就新增一个客户,并设置新客户的ID
        Customer customer = new Customer();
        customer.setIdNo(addAO.getIdNo());
        Customer dbCustomer = customerMapper.selectOne(customer);
        if (dbCustomer == null) {
        	//新增客户
        	BeanUtils.copyProperties(addAO, customer);
        	customer.setSex(CommonUtils.getSexByIdNo(addAO.getIdNo()));
        	customer.setPassword(CommonUtils.md5Passwod(Constants.USER_INIT_PASSWORD));
        	customer.setSource(Constants.CUSTOMER_SOURCE_FACE_SIGNATURE);
        	customer.setCreateTime(now);
        	customer.setUpdateTime(now);
        	customerMapper.insertSelective(customer);
        	customerId = customer.getId();
        	
        } else {
        	customerId = dbCustomer.getId();
        }
        
        order.setCustomerId(customerId);
        
        // 根据产品查询相应的期限、利率、金额、还款方式等
        OrderDefaultPropertiesDTO odpDto = productMapper.selectOrderDefaultProperties(addAO.getProductId(), addAO.getPeriods());
        state(odpDto != null, "保存订单失败，获取产品信息异常");
        order.setPeriods(addAO.getPeriods());
        order.setRate(odpDto.getRate());
        order.setRepayType(odpDto.getRepayType());
        //设置订单的代扣、佣金发放初始状态
        if (odpDto.getUseWithhold()) {
        	//如果该产品需要代扣
        	order.setWithholdStatus(OrderWithholdStatus.WITHHOLD_WAIT);
        } else {
        	order.setWithholdStatus(OrderWithholdStatus.UN_NEED);
        }
        if (odpDto.getUseCommission()) {
        	//如果需要返佣
        	order.setCommissionStatus(CommissionStatus.PAY_WAIT);
        } else {
        	order.setCommissionStatus(CommissionStatus.UN_NEED);
        }
        
        order.setUserId(dbBrokerUserInfo.getUserId());
        order.setApplyStatus(ApplyStatus.PROCESSING);
        order.setOrderStatus(OrderStatus.APPLY_SUCCESS);
        order.setCreateTime(now);
        order.setUpdateTime(now);
        //添加订单
        orderMapper.insertSelective(order);
        
        //更新客户联系人信息
  		List<CustomerContact> customerContactList = addAO.getCustomerContactList();
  		if(!CommonUtils.isEmpty(customerContactList)) {
  			for(CustomerContact customerContact : customerContactList) {
  				customerContact.setCustomerId(customerId);
  				customerContact.setCreateTime(now);
  				customerContact.setUpdateTime(now);
  			}
  			//批量新增
  			customerContactMapper.insertBatch(customerContactList);
  			//删除无效数据
  			customerContactMapper.deleteByUpdateTime(customerId, now);
  		}
        
        //指定分配接单员为当前管理员
        SpringContextUtils.getBean(OrderService.class).assignUser(order.getId(), managerId);
        
        //添加第一条审核数据类型，‘申请成功’
        OrderAuditRecord orderAuditRecord = new OrderAuditRecord();
    	orderAuditRecord.setOrderId(order.getId());
    	orderAuditRecord.setProcess(Process.APPLY);
    	orderAuditRecord.setResult(AuditResult.PASS);
    	orderAuditRecord.setRemark("通过");
    	orderAuditRecord.setManagerId(managerId);
    	orderAuditRecord.setCreateTime(now);
    	orderAuditRecord.setUpdateTime(now);
    	orderAuditRecordMapper.insertSelective(orderAuditRecord);
    	
    	//维护用户数据
    	UserOrderInfo userOrderInfo = new UserOrderInfo();
    	userOrderInfo.setUserId(order.getUserId());
    	userOrderInfo.setOrderCount(1);
    	userOrderInfo.setOrderLoanCount(0);
    	userOrderInfo.setLoanAmount(BigDecimal.ZERO);
    	userOrderInfo.setCreateTime(now);
    	userOrderInfoMapper.addUserOrderInfo(userOrderInfo);
    	
    	if (!odpDto.getUseWithhold() && !odpDto.getUseCommission()) {
    		//如果不需要代扣，也不需要返佣，则不设置代扣参数
    		return;
    	}
    	BigDecimal brokerRate = BigDecimal.ZERO;
    	if(dbBrokerUserInfo.getNewUser()) {
    		// 如果经纪人是新用户，处于3个月体验期（钻石经纪人），则佣金率应该按照钻石的来
    		brokerRate = brokerService.queryBrokerRate(BrokerLevel.DIAMOND);
    	}else {
    		brokerRate = brokerService.queryBrokerRate(dbBrokerUserInfo.getLevel());
    	}
    	OrderWithhold orderWithhold = new OrderWithhold();
    	orderWithhold.setOrderId(order.getId());
    	orderWithhold.setWithholdRate(odpDto.getUseWithhold() ? odpDto.getWithholdRate() : BigDecimal.ZERO);
    	orderWithhold.setCommissionRate(odpDto.getUseCommission() ? odpDto.getCommissionRate() : BigDecimal.ZERO);
    	orderWithhold.setBrokerRate(brokerRate);
    	orderWithhold.setCreateTime(now);
    	orderWithhold.setUpdateTime(now);
    	orderWithholdMapper.insertSelective(orderWithhold);
		
	}

	@Override
	public OrderDetailAdminVO selectOrderDetailAdminVO(Long orderId) {
		
		OrderDetailAdminVO modelVo = orderMapper.selectOrderDetailAdminVO(orderId);
		state(modelVo != null, "订单不存在");
		
		//查询客户联系人信息
		List<CustomerContactInfoVO> contactInfoList = customerContactMapper.selectCustomerContactInfoByCustomerId(modelVo.getCustomerId());
		contactInfoList.stream().forEach(c -> {
			c.setRelationshipText(c.getRelationship().getText());
		});
		
		modelVo.setContactInfoList(contactInfoList);
		return modelVo;
	}

	@Override
	@Transactional
	public void updateOrder(OrderAdminEditAO editAO) {
		Date time =  new Date();
		
		//更新订单信息
		Order updateOrder = new Order();
		BeanUtils.copyProperties(editAO, updateOrder);
		updateOrder.setId(editAO.getOrderId());
		updateOrder.setUpdateTime(time);
		orderMapper.updateByPrimaryKeySelective(updateOrder);
		
		//更新客户信息
		Customer updateCustomer = new Customer();
		BeanUtils.copyProperties(editAO, updateCustomer);
		updateCustomer.setId(editAO.getCustomerId());
		updateCustomer.setUpdateTime(time);
		customerMapper.updateByPrimaryKeySelective(updateCustomer);
		
		//更新客户联系人信息
		List<CustomerContact> customerContactList = editAO.getCustomerContactList();
		if(!CommonUtils.isEmpty(customerContactList)) {
			for(CustomerContact customerContact : customerContactList) {
				customerContact.setCustomerId(editAO.getCustomerId());
				customerContact.setCreateTime(time);
				customerContact.setUpdateTime(time);
			}
			//批量新增
			customerContactMapper.insertBatch(customerContactList);
			//删除无效数据
			customerContactMapper.deleteByUpdateTime(editAO.getCustomerId(), time);
		}
		
		
	}

	@Override
	public FurnitureGoodsOrderDetailAdminVO selectFurnitureGoodsOrderDetailAdminVO(Long orderId) {
		
		FurnitureGoodsOrderDetailAdminVO modelVo = orderMapper.selectFurnitureGoodsOrderDetailAdminVO(orderId);
		state(modelVo != null, "订单不存在");
		Long customerId = modelVo.getCustomerId();
		
		//查询订单购买证明
		List<OrderImageListVO> purchaseProofList = orderImageMapper.selectOrderImageListByOrderId(orderId, OrderImageType.PURCHASE_PROOF);
		if(!CommonUtils.isEmpty(purchaseProofList)) {
			purchaseProofList.stream().forEach(i -> {
				i.setSrc(fileService.getFileUrl(i.getPath(), Constants.MALL_BUCKET_NAME));
			});
		}
		
		//查询客户联系人信息
		List<CustomerContactInfoVO> contactInfoList = customerContactMapper.selectCustomerContactInfoByCustomerId(modelVo.getCustomerId());
		contactInfoList.stream().forEach(c -> {
			c.setRelationshipText(c.getRelationship().getText());
		});
		
		//查询客户房产证明
		List<CustomerImageListVO> housePropertyProofList = customerImageMapper.selectCustomerImageListByCustomerId(customerId, CustomerImageType.HOUSE_PROPERTY_PROOF);
		if(!CommonUtils.isEmpty(housePropertyProofList)) {
			housePropertyProofList.stream().forEach(i -> {
				i.setSrc(fileService.getFileUrl(i.getPath(), Constants.MALL_BUCKET_NAME));
			});
		}
		
		//查询客户结婚证明
		List<CustomerImageListVO> marriageProofList = customerImageMapper.selectCustomerImageListByCustomerId(customerId, CustomerImageType.MARRIAGE_PROOF);
		if(!CommonUtils.isEmpty(marriageProofList)) {
			marriageProofList.stream().forEach(i -> {
				i.setSrc(fileService.getFileUrl(i.getPath(), Constants.MALL_BUCKET_NAME));
			});
		}
		
//		Map<String, Object> map = JsonObjectMapper.read(modelVo.getBigDataCheckResponseJson(), Map.class);
//		modelVo.setBigDataCheckResponseMap(map);
		modelVo.setBigDataCheckResponseJson(null);
		modelVo.setSexText(modelVo.getSex().getText());
		modelVo.setAge(CommonUtils.getAgeByIdNo(modelVo.getIdNo()));
		modelVo.setBigDataCheckResultText(modelVo.getBigDataCheckResult().getText());
		modelVo.setFaceidCheckResultText(modelVo.getFaceidCheckResult().getText());
		modelVo.setPurchaseProofList(purchaseProofList);
		modelVo.setContactInfoList(contactInfoList);
		modelVo.setHousePropertyProofList(housePropertyProofList);
		modelVo.setMarriageProofList(marriageProofList);
		
		
		return modelVo;
	}

    
	
}
